package com.core.upfile;

import com.core.netty.http.work.HttpMyReponse;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.multipart.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Date;


/**
 * http 请求处理器
 * 2018/11/1.
 */

@ChannelHandler.Sharable
public class FileRequestHandler extends SimpleChannelInboundHandler<HttpObject> {
    private static final HttpDataFactory factory = new DefaultHttpDataFactory(true);
    private static String path="F:/tv/";

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject hob) throws Exception {

        long start = new Date().getTime();
        System.out.println(((HttpRequest)hob).uri());
        handleFile(ctx, hob);

        System.out.println("上传文件：" + (new Date().getTime() - start) / 1000 + "ms");

    }


    private void handleFile(ChannelHandlerContext cxt, HttpObject hob) throws Exception {
        HttpPostRequestDecoder httpDecoder = new HttpPostRequestDecoder(factory, (HttpRequest) hob);
        if (hob instanceof LastHttpContent) {
            System.out.println("lastHttpContent");
            writeChunk(cxt, httpDecoder);
            httpDecoder.destroy();
            httpDecoder = null;
            new HttpMyReponse(cxt).fullWrite("成功");
        }
    }

    private void writeChunk(ChannelHandlerContext cxt, HttpPostRequestDecoder httpDecoder) throws IOException {
        while (httpDecoder.hasNext()) {
            InterfaceHttpData data = httpDecoder.next();
            if (data != null && InterfaceHttpData.HttpDataType.FileUpload.equals(data.getHttpDataType())) {
                final FileUpload fileUpload = (FileUpload) data;
                final File file = new File(path + fileUpload.getFilename());

                try (FileChannel inputChannel = new FileInputStream(fileUpload.getFile()).getChannel();
                     FileChannel outputChannel = new FileOutputStream(file).getChannel()) {
                     outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
                    // ResponseUtil.response(ctx, request, new GeneralResponse(HttpResponseStatus.OK, "SUCCESS", null));
                }
            }
        }
    }


}